#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2011, Kyan He <kyan.ql.he@gmail.com>
#
# Last Modified:
#   Kyan He <kyan.ql.he@gmail.com> @ Fri Mar  4 00:28:57 CST 2011
#

import socket
import sys
import os
import re

HOST = ("www.baidu.com", 80)
# <span class="nums"> will return if there are no related keywords
#KEY_PREFIX=u'<span class="nums" style="margin-left:120px">找到相关结果'.encode('gb2312')
KEY_PREFIX=u'<span class="nums".*>找到相关结果'.encode('gb2312')
KEY_ABOUT=u'约'.encode('gb2312')
KEY_SUFFIX=u'个</span>'.encode('gb2312')
retag = re.compile("%s(%s)?([0-9,]+)%s" % (KEY_PREFIX, KEY_ABOUT, KEY_SUFFIX))

def get_rate(key='baidu'):
    s.send("GET /s?wd=%s HTTP/1.1\r\n" % key)
    s.send("HOST: www.baidu.com\r\n")
    s.send("\r\n")

    BUF_SZ = 1024 * 8
    f = open("baidu_%s" % key, 'w')
    while True:
        # TODO: quit from while
        data = s.recv(BUF_SZ)
        if len(data) == 0:
            print "close by remote?"
            return 0
        f.write(data)
        # treat data as "gb2312" to generate unicode represenation string
        # u = unicode(data, 'gb2312')
        match = retag.search(data)
        if not match is None:
            print "x"
            # KEY_ABOUT match
            if (len(match.groups()) == 2):
                # match.group(0) is the whole string matched
                return long(match.group(2).replace(',', ''))
            else:
                return long(match.group(1).replace(',', ''))
# worked
# retag = re.compile("%s([^0-9]*)([0-9,]+)%s" % (KEY_PREFIX, KEY_SUFFIX))
# why (%s?) wont match

if len(sys.argv) != 3:
    print 'Usage: fight <keyword1> <keyword2>'
    sys.exit(0)

key1 = sys.argv[1]
key2 = sys.argv[2]

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.connect(HOST)
except socket.error:
    print 'Cannot connect to ', HOST
    print socket.error
    sys.exit(0)

rate1 = get_rate(key1)
rate2 = get_rate(key2)

print "%s vs %s" % (rate1, rate2)
